package com.usernet.product.server;

import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.usernet.product.dao.SoftwareDao;
import com.usernet.product.entity.Search;
import com.usernet.product.entity.Software;
import com.usernet.product.tools.JSONTools;

public class SearchService {

	private SoftwareDao softwareDao = new SoftwareDao();

	/**
	 * 搜索[type=9]
	 */
	public String search(HttpServletRequest request) {
		String ret = null;
		try {
			String keyword = request.getParameter("keyword");
			int size = Integer.parseInt(request.getParameter("pageSize"));
			int no = Integer.parseInt(request.getParameter("pageNo"));
			List<Software> list = softwareDao.getAllSearch(size, no, keyword);
			int maxSize = 0;
			if (no == 1) {
				maxSize = softwareDao.getSearchCount(keyword);
			}
			// 增加搜索记录
			Search search = new Search();
			String tel = MarketUtils.getIpAddr(request);
			search.setTel(tel);
			search.setSearch(keyword);
			search.setTime(new Timestamp(System.currentTimeMillis()));
			search.setStatus(0);
			softwareDao.save(search);
			StringBuffer buf = new StringBuffer();
			buf.append("[");
			for (int i = 0; i < list.size(); i++) {
				Software software = list.get(i);
				buf.append("{");
				buf.append("id:");
				buf.append(software.getId());
				buf.append(",name:\"");
				buf.append(JSONTools.string2Json(software.getName()));
				buf.append("\",icon:\"");
				buf.append(software.getIcon());
				buf.append("\",develope:\"");
				buf.append(JSONTools.string2Json(software.getDevelope()));
				buf.append("\",avg:");
				buf.append(software.getAvg());
				buf.append("}");
				if (i < list.size() - 1) {
					buf.append(",");
				}
			}
			buf.append("],size:");
			buf.append(maxSize);
			ret = MarketUtils.getResJson(buf.toString());
		} catch (Exception ex) {
			ex.printStackTrace();
			ret = MarketUtils.getThrowJson();
		}
		return ret;
	}
}
